import React, { memo, useEffect, useRef, useState } from "react";
import ScrollViewWrapper from "./style";
import IconArrowLeft from "@/assets/svg/icon-arrow-left";
import IconArrowRight from "@/assets/svg/icon-arrow-right";
// import PropTypes from "prop-types";

const ScrollView = memo(function ScrollView(props) {
  const [isShowRightBtn, setisShowRightBtn] = useState(false);
  const [isShowLeftBtn, setisShowLeftBtn] = useState(false);
  const [positionIndex, setPositionIndex] = useState(0);
  const [canScrollWidth, setCanScrollWidth] = useState(0);
  const scrollEleRef = useRef();
  useEffect(() => {
    const scrollWidth = scrollEleRef.current.scrollWidth;
    const clientWidth = scrollEleRef.current.clientWidth;
    console.log("scrollWidth", scrollWidth);
    console.log("clientWidth", clientWidth);
    setisShowRightBtn(scrollWidth - clientWidth > 0);
    setCanScrollWidth(scrollWidth - clientWidth);
  }, [props.children]);

  function controlBtnClick(flag) {
    let newIndex = flag === "left" ? positionIndex - 1 : positionIndex + 1;
    const wrapEle = scrollEleRef.current.children[0];
    const offsetLeftWidth = wrapEle.children[newIndex].offsetLeft;
    wrapEle.style.transform = `translate(-${offsetLeftWidth}px)`;
    setPositionIndex(newIndex);
    setisShowRightBtn(canScrollWidth > offsetLeftWidth);
    setisShowLeftBtn(offsetLeftWidth > 0);
  }
  return (
    <ScrollViewWrapper>
      {isShowLeftBtn && (
        <div className="btn btn-left" onClick={() => controlBtnClick("left")}>
          <IconArrowLeft />
        </div>
      )}
      {isShowRightBtn && (
        <div className="btn btn-right" onClick={() => controlBtnClick("right")}>
          <IconArrowRight />
        </div>
      )}
      <div ref={scrollEleRef} className="scroll-view-content">
        {props.children}
      </div>
    </ScrollViewWrapper>
  );
});

ScrollView.propTypes = {};

export default ScrollView;
